package com.boarsoft.boar.config.drm.plugin;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alipay.drm.client.DRMClient;
import com.alipay.drm.client.api.model.DistributedResource;
import com.alipay.drm.client.api.model.DistributedResourceAttribute;
import com.alipay.drm.client.assembly.DistributedResourceAttributeHolder;
import com.alipay.drm.client.assembly.ResourceInitializer;
import com.alipay.drm.client.assembly.confreg.ConfregDataBuilder;
import com.boarsoft.boar.config.drm.listener.DrmConfigChangedListener;
import com.boarsoft.config.core.Config;
import com.boarsoft.config.manager.PropConfigManager;
import com.boarsoft.config.plugin.ConfigPlugin;

/**
 * 基于apollo-client封装的扩展插件
 *
 */
@Component("configPlugin")
public class DrmConfigPlugin implements ConfigPlugin {

    @Value("${spring.application.name}")
    private String appName;

    @Override
    public void init() {
        ConcurrentHashMap<String,Object> configMap= PropConfigManager.getAllResources();
        for(String resourceId:configMap.keySet()){
            DRMClient.getInstance().getResourceValueAsProperties("origien",appName,resourceId);
            Config config = new Config();
            config.setRegion("origien");
            config.setAppName(appName);
            config.setId(resourceId);
            List<String> attr=new ArrayList<>();
            for(Field f:configMap.get(resourceId).getClass().getDeclaredFields()) {
                attr.add(f.getName());
            }
            DRMClient.getInstance().registerResourceValueChangedListener(new DrmConfigChangedListener());
            DRMClient.getInstance().register(config,attr);
        }
    }

    @Override
    public void refresh() {
        ConcurrentHashMap<String,Object> configMap= PropConfigManager.getAllResources();
        for(String resourceId:configMap.keySet()){
            DistributedResource distributedResource=DRMClient.getInstance().findResourceByAppAndId(appName,resourceId);
            for(String key:distributedResource.getAttributes().keySet()){
                DistributedResourceAttribute attribute=distributedResource.getAttributes().get(key);
                String dataId= ConfregDataBuilder.buildDataId(attribute);
                DistributedResourceAttributeHolder.removeAttribute(dataId);
                ResourceInitializer.getInstance().initAttribute(attribute);
            }
        }
    }

}

